package com.eascs.workflow.timeEffective.service.impl;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.workflow.common.entity.wf.ProcessTaskMain;
import com.eascs.workflow.common.entity.wf.ProcessTaskNode;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.email.service.WFEmailService;
import com.eascs.workflow.timeEffective.dao.TimeffectiveDao;
import com.eascs.workflow.timeEffective.service.TaskServer;
import com.eascs.workflow.timeEffective.utils.CalculateTimeUtils;
import com.eascs.workflow.wf.dao.ProcessTaskNodeDao;

@Service
public class TaskServerImpl implements TaskServer {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private TimeffectiveDao timeffectiveDao;
	
	@Autowired
	private ProcessTaskNodeDao processTaskNodeDao;
	
	@Autowired
	private CalculateTimeUtils calculateTimeUtils;
	
	@Autowired
	private WFEmailService wfEmailService;
	
	private static final int threadPool = 5;

	/*@Override
	public ModelResult<Boolean> wfProcessNodeTask(List<ProcessTaskNode> list) {
		logger.info("----开始统计节点时效");
		ModelResult<Boolean> modelResult = new ModelResult<>();
		
		if (list == null || list.size() == 0) {
			logger.info("----暂时没有需要统计的数据");
			return modelResult.withError("wfProcessTask error list is null", "暂时没有发现要处理的数据");
		}
		
		int total = list.size();
		logger.info("----待统计节点时效数："+total);
		
		ExecutorService  fixedThreadPool = Executors.newFixedThreadPool(threadPool);
		
		for (ProcessTaskNode item : list) {
			fixedThreadPool.execute(new TaskThread(item));
		}
		
		fixedThreadPool.shutdown();
		
		logger.info("----结束统计节点时效");
		return modelResult.withModel(true);
	}*/
	
	@Override
	public ModelResult<Boolean> wfProcessNodeTask(ProcessTaskNode taskNode) {
		ModelResult<Boolean> modelResult = new ModelResult<>();
		try {
			logger.info("----开始统计节点时效");
			
			if (taskNode == null) {
				logger.info("----暂时没有需要统计的数据");
				return modelResult.withError("wfProcessTask error is null", "暂时没有发现要处理的数据");
			}
			Date t1=taskNode.getAuditorStartDate();
			Date t2=taskNode.getAuditorEndDate();
			String taskId=taskNode.getTaskNodeId();
			Integer timeEffective=taskNode.getTimeEffective();
			int nodeStatus=taskNode.getNodeStatus();
			
			if(timeEffective == null){
				logger.info("----TaskNodeId[{}]统计节点时效异常 e:[{}]",taskNode.getTaskNodeId(),"时效时间未空，请在流程模板中配置");
				return modelResult.withModel(true);
			}
			if(ProcessTaskNode.NODE_STATUS_AUDITING == nodeStatus){
				t2=new Date();//审核中  结束时间获取当前时间
			}
			
			try {
				if (t1 == null || t2 == null) {
					throw new RuntimeException();
				}
				
				float   hours = calculateTimeUtils.calculateHours(taskId,t1, t2);  // taskId 用于多线程日志查看
				boolean bool  = timeffectiveDao.updateUsedTime(taskNode.getTaskNodeId(), hours);
				
				if (hours > timeEffective && ProcessTaskNode.NODE_STATUS_AUDITING == nodeStatus) {
					logger.info(taskId+"----节点开始发送邮件,taskNodeId:[{}],节点用时:[{}]，节点时效:[{}] " ,taskNode.getTaskNodeId(),hours,timeEffective);
					wfEmailService.notifyEmailTimeEffective(taskNode);
					logger.info(taskId+"----节点结束发送邮件,taskNodeId:[{}],节点用时:[{}]，节点时效:[{}] " ,taskNode.getTaskNodeId(),hours,timeEffective);
				}
				
				if ( !bool ) {
					logger.info(taskId+"----节点修改失败,taskNodeId:[{}],节点用时:[{}],taskNode:[{}] " ,taskNode.getTaskNodeId(),hours,taskNode.toString());
				}else{
					logger.info(taskId+"----节点修改成功,taskNodeId:[{}],节点用时:[{}] " ,taskNode.getTaskNodeId(),hours);
				}
			} catch (Exception e) {
				logger.info(taskId+"----节点修改错误,taskNodeId:[{}],errMsg:[{}],taskNode:[{}] " ,taskNode.getTaskNodeId(),e.getMessage(),taskNode.toString());
			}
		
			logger.info("----结束统计节点时效");
		} catch (Exception e) {
			logger.info("----TaskNodeId[{}]统计节点时效异常 e:[{}]",taskNode.getTaskNodeId(),e);
		}
		
		return modelResult.withModel(true);
	}
	
	@Override
	public ModelResult<Boolean> wfProcessMainTask(ProcessTaskMain taskMain) {
		ModelResult<Boolean> modelResult = new ModelResult<>();
		try {
			logger.info("----开始统计流程时效");
			
			float timeEffective=0;
			float usedTime=0;
			float overtime=0;
			
			if (taskMain == null) {
				logger.info("----暂时没有需要统计的数据");
				return modelResult.withError("wfProcessMainTask error is null", "暂时没有发现要处理的数据");
			}
			
			try {
				//计算流程总用时，总超时 
				List<ProcessTaskNode> nodeList = processTaskNodeDao.getNodeListByTaskId(taskMain.getTaskId());
				
				for (ProcessTaskNode n : nodeList) {
					if (n.getTimeEffective() != null) {
						timeEffective += n.getTimeEffective();
					}
					if (n.getUsedTime() != null) {
						usedTime += n.getUsedTime();
					}
				}
				
				if(usedTime > timeEffective){
					overtime = usedTime - timeEffective;
				}
				
				boolean bool  = timeffectiveDao.updateWFMainUsedTime(taskMain.getTaskId(), usedTime, overtime);
				if ( !bool ) {
					logger.info("----流程修改失败,taskMainId:[{}],流程总用时:[{}],流程总超时:[{}] " ,taskMain.getTaskId(),usedTime,overtime);
				}else{
					logger.info("----流程修改成功,taskMainId:[{}],流程总用时:[{}],流程总超时:[{}]" ,taskMain.getTaskId(),usedTime,overtime);
				}
			} catch (Exception e) {
				logger.info("----流程修改错误,[{}]流程时效待统计数出错：[{}]",taskMain.getTaskId(),e.getMessage());
			}
			
			logger.info("----结束统计流程时效");
		} catch (Exception e) {
			logger.info("----TaskId[{}]统计流程时效异常 e:[{}]",taskMain.getTaskId(),e);
		}
		
		return modelResult.withModel(true);
	}
	
	/*class TaskThread implements Runnable{
		private ProcessTaskNode taskNode;
		
		TaskThread () {}
		
		TaskThread (ProcessTaskNode param){
			this.taskNode = param;
		}

		@Override
		public void run() {
			Date t1=taskNode.getAuditorStartDate();
			Date t2=taskNode.getAuditorEndDate();
			String taskId=taskNode.getTaskNodeId();
			int timeEffective=taskNode.getTimeEffective();
			
			if(ProcessTaskNode.NODE_STATUS_AUDITING == taskNode.getNodeStatus()){
				t2=new Date();//审核中  结束时间获取当前时间
			}
			
			try {
				if (t1 == null || t2 == null) {
					throw new RuntimeException();
				}
				
				float   hours = calculateTimeUtils.calculateHours(taskId,t1, t2);  // taskId 用于多线程日志查看
				boolean bool  = timeffectiveDao.updateUsedTime(taskNode.getTaskNodeId(), hours);
				
				if (hours > timeEffective) {
					logger.info(taskId+"----节点开始发送邮件,taskNodeId:[{}],节点用时:[{}]，节点时效:[{}] " ,taskNode.getTaskNodeId(),hours,timeEffective);
					wfEmailService.notifyEmailTimeEffective(taskNode);
					logger.info(taskId+"----节点结束发送邮件,taskNodeId:[{}],节点用时:[{}]，节点时效:[{}] " ,taskNode.getTaskNodeId(),hours,timeEffective);
				}
				
				if ( !bool ) {
					logger.info(taskId+"----节点修改失败,taskNodeId:[{}],节点用时:[{}],taskNode:[{}] " ,taskNode.getTaskNodeId(),hours,taskNode.toString());
				}else{
					logger.info(taskId+"----节点修改成功,taskNodeId:[{}],节点用时:[{}] " ,taskNode.getTaskNodeId(),hours);
				}
			} catch (Exception e) {
				logger.info(taskId+"----节点修改错误,taskNodeId:[{}],errMsg:[{}],taskNode:[{}] " ,taskNode.getTaskNodeId(),e.getMessage(),taskNode.toString());
			}
		
		}
		
	}*/

	

}
